﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wsitech.BLL;
using Wsitech.Model;
using System.Xml;

public partial class Backend_Config_NewsIndex : BackendPageBase
{
    public readonly string fileName = "/UploadFile/Image/newsIndex.jpg";
    public readonly string configPath = "/Config/NewsIndex.config";
    private readonly int indexWidth = 300;
    private readonly int indexHeight = 200;

    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void btnAdd_Click(object sender, EventArgs e)
    {
        TextInfo info = TextInfoBLL.Instance.GetActiveDetailByTitle(txtTitle.Text.Trim());
        if (info == null)
        {
            base.Alert("新闻不存在或已禁用！");
        }
        if (txtDesc.Text.Trim() == "")
        {
            base.Alert("简介不能为空！");
        }
        if (FileUpload1.HasFile)
        {
            System.Drawing.Image img = null;
            try
            {
                img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
                if (img != null)
                {
                    ImageProcess.ImageToProperSize(img, indexWidth, indexHeight, Server.MapPath(fileName));
                }

                SaveNewsIndexConfig(fileName, info.TextInfoId, txtDesc.Text.Trim());
                base.AlertGo("添加成功！", Request.Path);
            }
            catch (Exception)
            {
                if (img != null)
                {
                    img.Dispose();
                }
                throw;
            }
        }
        else
        {
            base.Alert("请上传图片！");
        }
    }

    private void SaveNewsIndexConfig(string fileName, string textinfoid, string description)
    {
        XmlDocument doc = new XmlDocument();

        //加载文件
        doc.Load(Server.MapPath(configPath));

        //根
        XmlNode root = doc.SelectSingleNode("config");

        //图片
        XmlNode image = root.SelectSingleNode("image");
        if (image != null)
        {
            image.InnerText = fileName;
        }
        //简介
        XmlNode desc = root.SelectSingleNode("description");
        if (desc != null)
        {
            desc.InnerText = description;
        }

        //新闻编号
        XmlNode news = root.SelectSingleNode("news");
        if (news != null)
        {
            news.InnerText = textinfoid;
        }

        //保存
        doc.Save(Server.MapPath(configPath));
    }
}